import os
import socket
from typing import List

import numpy as np
from pymilvus import connections

# 统一配置读取
OLLAMA_HOST = os.getenv("OLLAMA_HOST", "192.168.2.10")
OLLAMA_PORT = int(os.getenv("OLLAMA_PORT", "11434"))
EMBED_MODEL = os.getenv("EMBED_MODEL", "nomic-embed-text:latest")
EMBED_DIM = int(os.getenv("EMBED_DIM", "768"))
MILVUS_HOST = os.getenv("MILVUS_HOST", "192.168.2.10")
MILVUS_PORT = os.getenv("MILVUS_PORT", "19530")
COLLECTION_NAME = os.getenv("MILVUS_COLLECTION", "products_embeddings")


def check_tcp(host: str, port: int, timeout: float = 3.0) -> bool:


      
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(timeout)
    try:
        return sock.connect_ex((host, port)) == 0
    finally:
        sock.close()


def l2_normalize(vec: List[float]) -> List[float]:
    arr = np.array(vec, dtype=np.float32)
    return (arr / (np.linalg.norm(arr) + 1e-12)).tolist()


def connect_milvus():
    connections.connect(alias="default", host= MILVUS_HOST, port=MILVUS_PORT)


def ollama_embed(texts: List[str]) -> List[List[float]]:
    import ollama
    client = ollama.Client(host=f"http://{OLLAMA_HOST}:{OLLAMA_PORT}")
    out = []
    for t in texts:
        emb = client.embeddings(model=EMBED_MODEL, prompt=t)
        vec = emb.get("embedding")
        out.append(vec)
    return out
